package com.liquidhorse.gui;

import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;

import com.liquidhorse.core.TLEvent;
import com.liquidhorse.parser.HTMLParser;

public final class BrowserFrame extends JFrame {
	private static final long serialVersionUID = 1L;

	private final Tray tray = new Tray();
	private DefaultListModel<TLEvent> listModel = null;
	private final HTMLParser parser = new HTMLParser();
	private JList<TLEvent> list = null;
	
	public BrowserFrame() {
		super("LiquidHorse (Beta)");
		
		JPanel p = new JPanel();
		this.add(p);
		
		p.setLayout(new GridLayout(1, 1));
		
		this.listModel = new DefaultListModel<TLEvent>();
		
		list = new JList<TLEvent>(listModel);
		list.setCellRenderer(new HeavyRenderer());
	    list.addMouseListener(new MouseAdapter() {
	    	@Override
	        public void mouseClicked(MouseEvent mouseEvent) {
	          JList<TLEvent> theList = (JList<TLEvent>) mouseEvent.getSource();
	          if (mouseEvent.getClickCount() == 2) {
	            int index = theList.locationToIndex(mouseEvent.getPoint());
	            if (index >= 0) {
	              TLEvent event = theList.getModel().getElementAt(index);
	              try {
					java.awt.Desktop.getDesktop().browse(new URI("http://www.teamliquid.net/calendar/2012/04/#event_" + event.getId()));
				} catch (IOException e) {
					e.printStackTrace();
				} catch (URISyntaxException e) {
					e.printStackTrace();
				}
	            }
	          }
	        }
	      });
		
		JScrollPane listScroller = new JScrollPane(list);
		
		p.add(listScroller);
		
		this.refreshListModel();
		
		this.pack();
		
	    makeCellVisible();
		
		this.center();
		this.setDefaultCloseOperation(EXIT_ON_CLOSE);
		this.setState(JFrame.ICONIFIED);
		this.setVisible(false);
		
		list.addKeyListener(new KeyAdapter() {
			@Override
			public void keyPressed(KeyEvent e) {
				if (e.getKeyCode() == KeyEvent.VK_F5) {
					refreshListModel();
					makeCellVisible();
				}
			}
		});
		
		Runnable r = new Runnable() {
			@Override
			public void run() {
				String titleChain = null;;
				
				while (true) {
					titleChain = "";
					
					try {
						Thread.sleep(1000 * 60);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					for (int i = 0; i < listModel.size(); i++) {
						TLEvent e = listModel.getElementAt(i);
						e.addMinutes(-1);
						if (e.getRemainingMinutes() == 5) {
							titleChain += e.getTitle() + "\n";
						}
					}
					list.repaint();
					
					if (!titleChain.equals("")) {
						tray.showInfoMsg(titleChain, "Starting in 5 minutes");
					}
				}
			}
		};
	
		Thread t = new Thread(r);
		t.start();
		
		this.addWindowListener(new WindowListener() {
			@Override
			public void windowActivated(WindowEvent arg0) {}

			@Override
			public void windowClosed(WindowEvent arg0) {}

			@Override
			public void windowClosing(WindowEvent arg0) {}

			@Override
			public void windowDeactivated(WindowEvent arg0) {}

			@Override
			public void windowDeiconified(WindowEvent arg0) {}

			@Override
			public void windowIconified(WindowEvent arg0) {
				setVisible(false);
			}

			@Override
			public void windowOpened(WindowEvent arg0) {}	
		});
		
		this.tray.setTrayIcon(this);
		this.setIconImage(Toolkit.getDefaultToolkit().getImage(this.getClass().getClassLoader().getResource("icon.png")));
	}

	public void refreshListModel() {
		listModel.clear();
	
		for (TLEvent e : parser.getEvents()) {
			listModel.addElement(e);
		}
	}

	private void makeCellVisible() {
	    int firstRunningIndex = 0;
	    int lastRunningIndex = 0;
	    
	    for (int i = 0; i < listModel.getSize(); i++) {
	    	if (listModel.getElementAt(i).isRunning()) {
	    		if (firstRunningIndex == 0) {
	    			firstRunningIndex = i;
	    		}
	    		lastRunningIndex = i;
	    	}
	    }
	    
	    list.setVisibleRowCount(lastRunningIndex - firstRunningIndex + 1);
	    list.setSelectedIndex(firstRunningIndex);
	    list.ensureIndexIsVisible(lastRunningIndex + 1);
	}

	private void center() {
		final int frameWidth = this.getWidth();
		final int frameHeight = this.getHeight();
		final int screenWidth = (int) Toolkit.getDefaultToolkit().getScreenSize().getWidth();
		final int screenHeight = (int) Toolkit.getDefaultToolkit().getScreenSize().getHeight();
		
		this.setLocation(screenWidth / 2 - frameWidth / 2, screenHeight / 2 - frameHeight / 2);
	}
}
